﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="NumericSettingDescriptor.cs" company="Radical Research Ltd">
//   Copyright (c) Radical Research Ltd. The MIT License (MIT)
// </copyright>
// <summary>
//   
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace RadicalResearch.MiniState.Descriptors
{
    using System;
    using System.Globalization;

    /// <summary>Manages numeric setting values.</summary>
    public class NumericSettingDescriptor : StringSettingDescriptor
    {
        #region Constants and Fields

        /// <summary>
        ///   Type used to store bitmask
        /// </summary>
        private readonly Type type;

        #endregion

        #region Constructors and Destructors

        /// <summary>Initializes a new instance of the <see cref="NumericSettingDescriptor"/> class.</summary>
        /// <param name="valueKey">The value key.</param>
        /// <param name="isValidated">if set to <c>true</c> the setting is included in hash validation.</param>
        /// <param name="type">The type of numeric value.</param>
        public NumericSettingDescriptor(string valueKey, bool isValidated, Type type)
            : base(valueKey, isValidated)
        {
            this.type = type;
        }

        #endregion

        #region Public Methods

        /// <summary>Reads the value.</summary>
        /// <param name="values">The values.</param>
        /// <returns>The value as an object</returns>
        public override object ReadValue(IValueCollection values)
        {
            string hex = (string)base.ReadValue(values);
            long value = 0;
            if (!string.IsNullOrEmpty(hex) && long.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out value))
            {
                value = long.Parse(hex, NumberStyles.HexNumber);
            }

            return Convert.ChangeType(value, this.type);
        }

        /// <summary>Writes the value.</summary>
        /// <param name="values">The values.</param>
        /// <param name="value">The value.</param>
        public override void WriteValue(IValueCollection values, object value)
        {
            long number = Convert.ToInt64(value);
            string hex = Convert.ToString(number, 16);
            base.WriteValue(values, hex);
        }

        #endregion
    }
}